package com.capgemini.poste.metier;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.capgemini.poste.dao.Event;
import com.capgemini.poste.dao.Software;

public class Produit {

	static HashSet<Software> produits = new HashSet<Software>() ;
	static int maxNb = 0 ;
	
	public Produit( EntityManager em ) {
		// Create the query and populate the Hashset with users retrieved from DTB
		Query getAllSoftware = em.createQuery("select s from Software s" ) ;
		@SuppressWarnings("unchecked")
		List<Software> results = getAllSoftware.getResultList() ;
		for ( Software result : results ) {
			if ( result.getNb() >= maxNb ) {
				maxNb = result.getNb() ;
			}
			produits.add(result) ;
		}

	}

	public ArrayList<Event> retrieve(XSSFSheet excelSheet) {
		// TODO Auto-generated method stub
		XSSFRow row ;
		boolean bFirst = true ;
		ArrayList<Event> events = new ArrayList<Event> () ;
		
		for ( Iterator<Row> rowIterator = excelSheet.rowIterator(); rowIterator.hasNext();) {
			row = (XSSFRow)rowIterator.next() ;
			// Skip the header row
			if ( bFirst == true) {
               row = (XSSFRow) rowIterator.next();
               bFirst = false ;
            }
			
			Software software = new Software() ;
			software.setLb(row.getCell(3).getStringCellValue().toUpperCase()) ;
					
			if ( produits.contains(software) == false ) {
				software.setNb(++maxNb) ;
				if ( produits.add ( software ) == true ) {
					System.out.println ( "Produit  " + software.getLb() + " has been added !!");
					Event event = new Event () ;
					event.setType(POSTE.PRODUIT) ;
					event.setCd(software.getLb()) ;
					events.add(event) ;
				}
			}
		}
		return events ;
	}

	public ArrayList<Event> retrieve (XSSFWorkbook excelWorkbook ) {
		// TODO Auto-generated method stub
		return this.retrieve(excelWorkbook.getSheetAt(0)) ;
	}
	
	public int getSize ( ) {
		return produits.size() ;
	}
	
	public void save ( EntityManager em ) {
		for ( Iterator<Software> p = produits.iterator(); p.hasNext() ;) {
			em.persist(p.next()) ;
		}
	}
	
	public Software get ( String Cd ) {
		Software soft = new Software () ;
		
		for ( Iterator<Software> s = produits.iterator(); s.hasNext() ;) {
			soft = s.next() ;
			if ( soft.getLb().equals(Cd) == true ) {
				break ;
			}
		}		
		
		return soft ;
	}
	
}
